<template>
  <container title="应用模板-设计">
    <div class="tbc-flex-row" style="width: 100%">
      <div class="main-card" style="width:360px;">
        <div style="height:545px">
          <preview ref="view" :layoutId="layoutId" v-model="layout" @selected="onLayoutClick"
                   @delete="onLayoutDelete"/>
        </div>
      </div>
      <div style="margin-left: 20px;flex: 1">
        <div class="main-card" style="width: 100%">
          <template-component ref="component" @add="addComponent" @setting="showSetting"/>
          <div style="height: 40px"></div>
          <setting ref="setting" :id="layoutId" @change="onComponentEdit"/>
          <div>
            <el-button type="primary" @click="formSubmit">保存</el-button>
            <!--            <el-button onclick="history.back()">返回</el-button>-->
          </div>
        </div>
      </div>
    </div>


    <!--    <div class="wrapper">-->
    <!--      <el-button type="primary" @click="formSubmit">保存</el-button>-->
    <!--      <el-button onclick="history.back()">返回</el-button>-->
    <!--    </div>-->
  </container>
</template>
<script lang="ts">
import {
  defineComponent, defineAsyncComponent, reactive, toRefs,
  ref, Ref, onMounted
} from 'vue'
import {useRoute} from "vue-router";
import http from '@/plugin/http'
import {ElMessage} from 'element-plus'
import designBuilder from "./utils/designBuilder";
export default defineComponent({

  name: 'app-template-design',

  components: {
    TemplateComponent: defineAsyncComponent(() => import('./components/TemplateComponent.vue')),
    Preview: defineAsyncComponent(() => import('./components/Preview.vue')),
    Setting: defineAsyncComponent(() => import('./components/Setting.vue')),
  },


  setup() {
    const setting: Ref = ref(null)
    const view: Ref = ref(null)
    const component: Ref = ref(null)

    const route = useRoute()
    const state = reactive({
      tabIndex: 'form',
      form: {template_id: route.query.id || ''},
      layout: [],
      layoutIndex: -1,
      layoutId: '',
      dynamicForm: [
        {label: '模版名称', type: 'input', field: 'template_name', value: ''},
        {label: '页面路径', type: 'input', field: 'page', value: ''},
        {label: '模板预览', type: 'file', field: 'sketch', value: ''},
      ],
      setting: []
    })

    // 添加组件
    const addComponent = (data) => {
      data.id = (new Date()).getTime() as any
      (state.layout as any).push(data)
      state.layoutId = data.id
      onLayoutClick(data.id)
      setting.value.onChangeForm()
    }

    // 组件数据改变
    const onComponentEdit = (index, data) => {
      console.log('onComponentEdit', index, data)
      // if (state.layoutIndex < 0) return this.$refs.view.setting(data)
      const layout = state.layout.find(item => item.id == state.layoutId)
      view.value.init(layout, state.layoutId)
    }

    // 组件被点击
    const onLayoutClick = (id: string) => {
      state.layoutId = id
      const layout = state.layout.find(item => item.id == state.layoutId)
      setting.value.init(layout)
    }

    const showSetting = () => {
      console.log('showSetting')
    }

    const onLayoutDelete = () => {
      console.log('onLayoutDelete')
    }

    const formSubmit = async () => {
      const form = JSON.parse(JSON.stringify(state.form))
      state.dynamicForm.forEach(item => form[item.field] = item.value)
      const module = []
      state.layout.forEach(item => {
        module.push({type: item.type, config: item.config, data: item.data})
      })
      // module.push({type: 'background', config: this.setting.config, data: []})
      form.module = JSON.stringify(module)
      // form.config = JSON.stringify(state.setting.config)
      const api = form.template_id ? 'edit' : 'add'
      const res = await http.post('/app.template/' + api, form)
      if (res.data.code !== 0) return ElMessage.error(res.data.message)
      ElMessage.success(res.data.message)
    }

    const getTemplateInfo = async () => {
      if (!state.form.template_id) return;
      const res = await http.get('/app.template/detail', {
        template_id: state.form.template_id
      })
      if (res.data.code !== 0) return ElMessage.error(res.data.message)
      let data = res.data.data
      state.dynamicForm.forEach(item => {
        if (data[item.field] !== undefined) item.value = data[item.field]
      })
      const components = []
      const module = JSON.parse(data.module)
      module.forEach(item => components.push(component.value.create(item)))
      components.forEach(item => item.config = designBuilder.getConfig(item))
      console.log(components)
      state.layout = components
      setTimeout(() => {
        components.forEach((item, index) => {
          view.value.init(item, item.id)
        })
      }, 100)
      // this.dynamicForm.forEach(item => {
      //   if (typeof data[item.field] !== 'undefined') item.value = data[item.field]
      // })
      // if (data.config) {
      //   let setting = this.$refs.com.getSetting(JSON.parse(data.config))
      //   setTimeout(() => {
      //     this.showSetting(setting.background)
      //   }, 100)
      // }
    }
    //
    onMounted(() => {
      getTemplateInfo()
    })
    return {
      ...toRefs(state),
      setting,
      view,
      component,
      addComponent,
      onComponentEdit,
      showSetting,
      formSubmit,
      onLayoutClick,
      onLayoutDelete
    }
  }

  // mounted() {
  //   this.getTemplateInfo()
  // },

  // methods: {
  //
  //   // 显示配置
  //   showSetting(data) {
  //     console.log(data)
  //     this.setting = data
  //     this.$refs.setting.init(data)
  //   },
  //

  //

  //
  //   // 编辑组件
  //   onComponentEdit(index, data) {
  //     if (this.layoutIndex < 0) return this.$refs.view.setting(data)
  //     this.$refs.view.init(this.layout[this.layoutIndex], this.layoutIndex)
  //   },
  //
  //   // 组件删除
  //   onLayoutDelete(index) {
  //     this.layoutIndex = -1
  //     this.layout.splice(index, 1)
  //   },
  //
  //   async getTemplateInfo() {
  //     if (!this.form.template_id) return;
  //     const res = await this.http.get('/app.template/detail', {
  //       template_id: this.form.template_id
  //     })
  //     if (res.data.code !== 0) return this.$message.error(res.data.message)
  //     let data = res.data.data
  //     this.dynamicForm.forEach(item => {
  //       if (data[item.field] !== undefined) item.value = data[item.field]
  //     })
  //     let components = []
  //     let module = JSON.parse(data.module)
  //     module.forEach(item => components.push(this.$refs.com.create(item)))
  //     components.forEach(item => item.config = this.$refs.setting.getConfig(item))
  //     this.layout = components
  //     components.forEach((item, index) => this.$refs.view.init(item, index))
  //     this.dynamicForm.forEach(item => {
  //       if (typeof data[item.field] !== 'undefined') item.value = data[item.field]
  //     })
  //     if (data.config) {
  //       let setting = this.$refs.com.getSetting(JSON.parse(data.config))
  //       setTimeout(() => {
  //         this.showSetting(setting.background)
  //       }, 100)
  //     }
  //   },
  //
  //   showMainForm() {
  //     this.$refs.dialog.show()
  //   },
  //
  //   async formSubmit() {
  //     let form = JSON.parse(JSON.stringify(this.form))
  //     this.dynamicForm.forEach(item => form[item.field] = item.value)
  //     let module = []
  //     this.layout.forEach(item => {
  //       module.push({type: item.type, config: item.config, data: item.data})
  //     })
  //     // module.push({type: 'background', config: this.setting.config, data: []})
  //     form.module = JSON.stringify(module)
  //     form.config = JSON.stringify(this.setting.config)
  //     const api = form.template_id ? 'edit' : 'add'
  //     const res = await this.http.post('/app.template/' + api, form)
  //     if (res.data.code !== 0) return this.$message.error(res.data.message)
  //     this.$message.success(res.data.message)
  //   }
  // },
})
</script>
